class NumRoll {
  constructor(option = {}) {
    this.el = document.getElementById(option.id);
    console.log(this.el);
    this.initHtml();
    this.uls = this.el.querySelectorAll("ul");
    this.bindEvent();
    setInterval(()=>{
        numRoll.run();
    })
  }
  data = [0, 0, 0];

  setData(data) {
    const arr = Array.from(data + "");
    this.data = arr.map((num) => {
      return Number(num);
    });
  }
  initHtml() {
    const htmls = [];
    const data = this.data;
    for (let i = 0; i < data.length; i++) {
      let lis = [];
      for (let j = 0; j < 10; j++) {
        lis.push(`<li>${j}</li>`);
      }
      htmls.push(`
            <div class="item">
                <ul num="${data[i]}">${lis.join("")}</ul>
            </div>
            `);
    }
    this.el.innerHTML = htmls.join("");
  }

  runOneNum(num, index) {
    const numHeight = 20;
    const ul = this.uls[index];
    const prevNum = Number(ul.getAttribute("num"));
    let course = num - prevNum;
    if (prevNum > num) {
      course = 10 - prevNum + num;
    }
    ul.setAttribute("num", num);
    const dis = -course * numHeight + "px";
    ul.style.transform = `translate3d(0,${dis},0)`;
  }

  run() {
    this.data.forEach((num, index) => {
      this.runOneNum(num, index);
    });
  }

  /* 绑定滚动结束 */
  bindEvent() {
    this.uls.forEach((ul) => {
      ul.addEventListener("transitionend", () => {
        const num = Number(ul.getAttribute("num"));
        console.log(num);

        this.renderBottomNum(ul, num);
      });
    });
  }

  renderBottomNum(ul, num) {
    const htmls = [];
    for (let i = num; i < num + 10; i++) {
      const showNum = i > 9 ? i - 10 : i;
      htmls.push(`<li>${showNum}</li>`);
    }
    ul.innerHTML = htmls.join("");
    this.backToInitPos(ul);
  }
  /* 重新惠东初始位置 */
  backToInitPos(ul) {
    ul.style.transitionDuration = "0s";
    ul.style.transform = "translate3d(0, 0, 0)";
    setTimeout(() => {
      ul.style.transitionDuration = "1.5s";
    }, 10);
  }
}
 const numRoll = new NumRoll({
  id: "Tag",
});

setTimeout(() => {
  numRoll.setData(12365);
}, 2000);
